import React, { useState, useEffect } from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  Alert,
  KeyboardAvoidingView,
  Platform,
  ActivityIndicator,
} from 'react-native';
import { useNavigation, useRoute } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { RouteProp } from '@react-navigation/native';
import { useTheme } from '../../contexts/ThemeContext';
import { AuthStackParamList } from '../../navigation/AuthNavigator';
import { authAPI } from '../../services/api';

type ForgotPasswordScreenNavigationProp = StackNavigationProp<AuthStackParamList, 'ForgotPassword'>;
type ForgotPasswordScreenRouteProp = RouteProp<AuthStackParamList, 'ForgotPassword'>;

const ForgotPasswordScreen: React.FC = () => {
  const navigation = useNavigation<ForgotPasswordScreenNavigationProp>();
  const route = useRoute<ForgotPasswordScreenRouteProp>();
  const { colors } = useTheme();
  
  const [email, setEmail] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  // 如果从登录页面传递了邮箱，自动填充
  useEffect(() => {
    if (route.params?.email) {
      setEmail(route.params.email);
    }
  }, [route.params?.email]);

  const handleResetPassword = async () => {
    // 输入验证
    if (!email.trim()) {
      Alert.alert('错误', '请输入邮箱地址');
      return;
    }

    // 邮箱格式验证
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(email.trim())) {
      Alert.alert('错误', '请输入正确的邮箱格式');
      return;
    }

    setIsLoading(true);

    try {
      // 调用真实重置密码API
      const response = await authAPI.forgotPassword(email.trim());
      
      if (response.data.success) {
        Alert.alert('成功', '重置密码邮件已发送，请查收您的邮箱', [
          { 
            text: '确定', 
            onPress: () => navigation.navigate('Login') 
          }
        ]);
      } else {
        throw new Error(response.data.message || '发送失败');
      }
    } catch (error: any) {
      let errorMessage = '发送失败，请重试';
      
      if (error.response) {
        // 服务器返回错误
        const status = error.response.status;
        if (status === 400) {
          errorMessage = '邮箱格式不正确';
        } else if (status === 404) {
          errorMessage = '该邮箱未注册';
        } else if (status === 429) {
          errorMessage = '请求过于频繁，请稍后再试';
        } else if (status === 500) {
          errorMessage = '服务器内部错误，请稍后重试';
        } else if (status === 0 || status === 'NETWORK_ERROR') {
          errorMessage = '网络连接失败，请检查网络设置';
        }
      } else if (error.request) {
        // 网络请求失败
        errorMessage = '网络连接失败，请检查网络设置';
      } else if (error.message) {
        // 其他错误
        errorMessage = error.message;
      }
      
      Alert.alert('发送失败', errorMessage);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <KeyboardAvoidingView 
      style={[styles.container, { backgroundColor: colors.background }]}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
    >
      <View style={styles.content}>
        <Text style={[styles.title, { color: colors.text }]}>重置密码</Text>
        <Text style={[styles.subtitle, { color: colors.textSecondary }]}>
          请输入您的邮箱地址，我们将发送重置密码的链接
        </Text>

        <View style={styles.form}>
          <TextInput
            style={[styles.input, { 
              backgroundColor: colors.surface,
              color: colors.text,
              borderColor: colors.border,
            }]}
            placeholder="邮箱地址"
            placeholderTextColor={colors.textSecondary}
            value={email}
            onChangeText={setEmail}
            keyboardType="email-address"
            autoCapitalize="none"
            autoCorrect={false}
            editable={!isLoading}
          />

          <TouchableOpacity
            style={[
              styles.resetButton, 
              { 
                backgroundColor: isLoading ? colors.border : colors.primary,
                opacity: isLoading ? 0.7 : 1
              }
            ]}
            onPress={handleResetPassword}
            disabled={isLoading}
          >
            {isLoading ? (
              <ActivityIndicator color="#FFFFFF" size="small" />
            ) : (
              <Text style={styles.resetButtonText}>发送重置邮件</Text>
            )}
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.backToLogin}
            onPress={() => navigation.navigate('Login')}
            disabled={isLoading}
          >
            <Text style={[styles.backToLoginText, { color: colors.primary }]}>
              返回登录
            </Text>
          </TouchableOpacity>
        </View>
      </View>
    </KeyboardAvoidingView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  content: {
    flex: 1,
    justifyContent: 'center',
    paddingHorizontal: 20,
  },
  title: {
    fontSize: 28,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 8,
  },
  subtitle: {
    fontSize: 16,
    textAlign: 'center',
    marginBottom: 40,
    lineHeight: 24,
  },
  form: {
    width: '100%',
  },
  input: {
    height: 50,
    borderWidth: 1,
    borderRadius: 8,
    paddingHorizontal: 16,
    marginBottom: 24,
    fontSize: 16,
  },
  resetButton: {
    height: 50,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
  },
  resetButtonText: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: '600',
  },
  backToLogin: {
    alignItems: 'center',
    marginTop: 24,
  },
  backToLoginText: {
    fontSize: 16,
    fontWeight: '500',
  },
});

export default ForgotPasswordScreen; 